import { Button, Input } from 'antd-mobile'
import React, { useState } from 'react'
import { useSocket } from '../../hooks/useSocket'

let wss
function Chat() {
    const user_id=1,server_id=1314;
    const [value,setValue]=useState("");
    const [list,setList]=useState([]);
    useSocket({user_id,server_id},(ws)=>{
        ws.send(JSON.stringify({
            type:"getChatList",
            data:{
                user_id,
                server_id,
            }
        }))
        ws.onmessage=(e)=>{
            const {type,data}=JSON.parse(e.data)
            if(type==="getChatList"){
                setList(data)
            }
            else if(type==="addMessage"){
                setList(list=>list.concat(data))
            }
            console.log(data)
        }
        wss=ws
    })
    const handleSubmit=()=>{
        ws.send(JSON.stringify({
            type:"addMessage",
            data:{
                user_id,
                server_id,
                message:value
            }
        }))
    }
  return (
    <div>
      <div className="header">聊天</div>
      <div className="main">
        {
            list.map((v,i)=>{
                const myName=v.dir===1 ? 'right' : 'left'
                const avatar=v.dir===1 ? v.user_avatar : v.server_avatar
                return <div className={myName} key={i}>
                            <div className="avatar">
                                <img src={avatar} alt="" />
                            </div>
                            <div className="info">{v.message}</div>
                        </div>
            })
        }
        {/* <div className="right">
            <div className="avatar">
                <img src="../public/02.webp" alt="" />
            </div>
            <div className="info">所发生的讲话稿发</div>
        </div> */}
      </div>
      <div className="fotter">
        <Input className='text' value={value} onChange={e=>setValue(e)}></Input>
        <Button onClick={()=>handleSubmit()}>发送</Button>
      </div>
    </div>
  )
}

export default Chat
